#include <iostream>
#include <string>

using namespace std;

class Trie {
public:

    struct Node {
        Node* next[26];
        bool isEnd;

        Node() {
            for(int i = 0; i<26; i++) next[i] = nullptr;
            isEnd = false;
        }
    };

    Node* root;

    /** Initialize your data structure here. */
    Trie() {
        root = new Node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        // search starts;
        Node* iter = root;
        int i;
        for (i = 0; i< word.length(); i++) {
            if (iter->next[word[i] - 'a']) {
                iter = iter->next[word[i] - 'a'];
            } else
                break;
        }
        // construct node
        for (int j = i; j < word.length(); j++) {
            Node* newNode = new Node();
            iter->next[word[j] - 'a'] = newNode;
            iter = newNode;
        }
        // isEnd
        iter->isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Node* iter = root;
        for (int i = 0; i< word.length(); i++) {
            if (iter->next[word[i] - 'a']) {
                iter = iter->next[word[i] - 'a'];
            } else
                return false;
        }
        return iter->isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Node* iter = root;
        for (int i = 0; i< prefix.length(); i++) {
            if (iter->next[prefix[i] - 'a']) {
                iter = iter->next[prefix[i] - 'a'];
            } else
                return false;
        }
        for (int i = 0; i< 26; i++) {
            if (iter -> next[i]) {
                return true;
            }
        }
        return iter->isEnd ;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * bool param_2 = obj.search(word);
 * bool param_3 = obj.startsWith(prefix);
 */

 int main() {
    Trie trie = Trie();
    trie.insert("apple");
    cout << trie.search("apple");   // 返回 true
    cout << trie.search("app");     // 返回 false
    cout << trie.startsWith("app"); // 返回 true
    trie.insert("app");   
    cout << trie.search("app");     // 返回 true
}